#ifndef ROOMS_H
#define ROOMS_H

#include "postgresql/libpq-fe.h";
#include "table.h";
#include "iostream";
#include "time.h";

#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>

using namespace std;

class Rooms : public Table
{
	public:
		Rooms ( ) : Table ( ) { }

		int Create( )
		{
			PGresult * res = PQexec( conn, "CREATE TABLE rooms ( id serial NOT NULL, name character varying(32) NOT NULL UNIQUE );" );
			int result = PQresultStatus( res );
			if ( PQresultStatus( res ) == PGRES_COMMAND_OK )
				result = DB_OK;
			else
				result = DB_NO_RESULT;
			PQclear( res );
			return result;
		}

		int Clean( )
		{
			PGresult * res = PQexec( conn, "DROP TABLE rooms;" );
			//			cout << PQresultStatus( res ) << endl;
			int result = PQresultStatus( res );
			if ( PQresultStatus( res ) == PGRES_COMMAND_OK )
				result = DB_OK;
			else
				result = DB_NO_RESULT;
			PQclear( res );
			return result;
		}

		int FindRecord( char * name, int & id ) //
		{
			char st1[ 120 ] = "SELECT id FROM rooms WHERE name = '";
			char st3[ ] = "' LIMIT 1;";

			strncat( st1, name, 32 );
			strncat( st1, st3, 10 );

			PGresult * res = PQexec( conn, st1 );
			int result = PQresultStatus( res );
//			cout << "\t\t" << result << endl;
			if ( PQresultStatus( res ) == PGRES_TUPLES_OK )
			{
				if ( PQntuples( res ) )
				{
					result = DB_OK;
					char * endptr;
					id = strtol( PQgetvalue( res, 0, 0 ), &endptr, 10 ); // не проверяем.
				}
				else
				{
					result = DB_NO_RECORD;
					id = 0;
				}
			}
			else
			{
				result = DB_NO_RESULT;
				id = 0;
			}
//			cout << "idsession " << idsession << "\t" << result << endl;
			PQclear( res ); // ???
			return result;
		}

		int InsRecord( char * name ) //
		{
			int result;

//			cout << "InsRecord( ) idsession = " << idsession << endl;

			char st1[ 120 ] = "INSERT INTO rooms (name) VALUES ('";
			char st2[ 32 ];
			char st3[ 4 ] = "');";

			strncat( st1, name, 32 );
			strncat( st1, st3, 3);

			PGresult * res = PQexec( conn, st1 );
//			cout << st1 << endl;
			if ( PQresultStatus( res ) == PGRES_COMMAND_OK )
				result = DB_OK;
			else
				result = DB_NO_RESULT;
			PQclear( res );


//			cout << "InsRecord( ) idsession = " << idsession << endl;

			return result;
		}

};

#endif // ROOMS_H
